<template>
  <Row class="data-dictionary">
    <Col span="4" class="col-height100">
      <p>
        <Select
          v-model="searchParams.dictEngineeringType"
          ref="treeSelect"
          placeholder="请选择工程类型"
        >
          <Option
            v-for="item in list"
            :value="item.code"
            :key="item.code"
            style="display: none;"
            >{{ item.title }}</Option
          >
          <Tree
            :data="engineeringTypeList"
            style="padding-left:10px;"
            @on-select-change="checkEng"
          ></Tree>
        </Select>
      </p>
      <div>
        <!-- <span style="padding-left: 10px"><Icon type="ios-arrow-down" /> <span>标准WBS</span></span>-->
        <Tree
          :data="wbsList"
          ref="Tree"
          :load-data="loadData"
          style="padding-left:10px"
          @on-select-change="checkWbBtn"
        ></Tree>
      </div>
    </Col>
    <Col span="20" class="col-main">
      <div class="button-s">
        <Button
          type="primary"
          v-if="addBtnShow"
          @click="addBtn('add', '1', '新增')"
          >新增</Button
        >
        <Button
          type="primary"
          v-if="importBtnShow"
          @click="addBtn('import', '1', '标准WBS导入')"
          >导入</Button
        >
        <Button type="primary" v-if="deleteBtnShow" @click="deleteBtn"
          >删除</Button
        >
      </div>
      <Table
        border
        ref="selection"
        :columns="columns"
        :data="dictList"
        @on-select="selectRiado"
        @on-select-all="selectRiadoAll"
        @on-select-cancel="selectCancel"
        @on-select-all-cancel="selectAllCancel"
      >
        <template slot-scope="{ row, index }" slot="action">
          <span
            title="编辑"
            class="button-class"
            v-if="editoBtnShow"
            type="text"
            @click="addBtn('editor', row.id, '编辑', row.code)"
            >编辑</span
          >
          <span
            title="详情"
            class="button-class"
            type="text"
            @click="addBtn('details', row.id, '详情', row.code)"
            >详情</span
          >
        </template>
      </Table>
      <Page
        class="tab-page"
        :total="page.total"
        :current="page.current"
        :page-size="page.pageSize"
        @on-change="pageChange"
        @on-page-size-change="sizeChange"
        show-elevator
        show-sizer
        show-total
      />
    </Col>
  </Row>
</template>

<script>
  import { mapActions } from 'vuex'
export default {
  name: 'StandardLibrary',
  data() {
    return {
      addBtnShow: false,
      importBtnShow: false,
      deleteBtnShow: false,
      editoBtnShow: false,
      searchParams: {
        dictEngineeringType: ''
      },
      list: [], //工程类型SELECT选择
      list1: [], //专业类型SELECT选择
      engineeringTypeList: [],
      wbsList: [], //专业类型
      parentId: '0',
      typeCode: '',
      deleteList: [],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '序号',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h(
              'span',
              params.index + (this.page.current - 1) * this.page.pageSize + 1
            )
          }
        },
        {
          title: '名称',
          key: 'name',
          align: 'center'
        },
        {
          title: '操作',
          width: 150,
          align: 'center',
          slot: 'action'
        }
      ],
      dictList: [],
      typeList: [],
      nodeItem:'',
      page: {
        total: 0,
        current: 1,
        pageSize: 10,
        totalPage: 0
      }
    }
  },
  methods: {
    ...mapActions(['handleOperation', 'handleNode']),
    //code码生成
    getProfessionalTypecodeGenerate(
      dictEngineeringType,
      parentId,
      type,
      id,
      name
    ) {
      this.$api.standardLibrary
        .getProfessionalTypecodeGenerate(dictEngineeringType, parentId)
        .then(res => {
          if (res.code === 200) {
            this.$router.push({
              path: `standard-wbs/standard-wbs/${type}/${id}/${name}`,
              query: {
                current: this.page.current,
                pageSize: this.page.pageSize,
                dictEngineeringType: this.searchParams.dictEngineeringType,
                parentId: this.parentId,
                code: res.data
              }
            })
          } else {
            this.$Message.error(res.message)
          }
        })
    },
    addBtn(type, id, name, code) {
      if (type === 'import') {
        this.$router.push({
          path: `standard-wbs/standard-import/${type}/${id}/${name}`,
          query: {
            current: this.page.current,
            pageSize: this.page.pageSize
          }
        })
      } else if (type === 'add') {
        if (!this.searchParams.dictEngineeringType) {
          this.$Message.warning('请先选择工程类型')
          return
        }if (this.nodeItem.level>=5) {
          this.$Message.warning('最多只能创建5级')
          return
        }
        this.getProfessionalTypecodeGenerate(
          this.searchParams.dictEngineeringType,
          this.parentId,
          type,
          id,
          name
        )
      } else {
        this.$router.push({
          path: `standard-wbs/standard-wbs/${type}/${id}/${name}`,
          query: {
            current: this.page.current,
            pageSize: this.page.pageSize,
            dictEngineeringType: this.searchParams.dictEngineeringType,
            parentId: this.parentId,
            code: code
          }
        })
      }
    },
    //删除
    deleteBtn() {
      if (this.deleteList.length <= 0) {
        this.$Message.warning('请选择要删除的数据')
        return false
      }
      const deleteList = []
      this.deleteList.forEach(val => {
        let obj = {}
        obj.id = val.id
        obj.typeId = val.typeId
        obj.code = val.code
        obj.name = val.name
        obj.description = val.description
        deleteList.push(obj)
      })
      this.$Modal.confirm({
        title: '温馨提示',
        closable: true,
        content: '确认删除吗？',
        width: 360,
        onOk: () => {
          this.$api.standardLibrary
            .getProfessionalTypeDelete(this.deleteList)
            .then(res => {
              if (res.code === 200) {
                this.$Message.success(res.message)
                this.getWbsTabelList(this.parentId)
                this.getWbsList(this.searchParams.dictEngineeringType)
              } else {
                this.$Message.error(res.message)
              }
            })
        }
      })
    },

    //获取工程类型
    getEngineeringType() {
      let code = 'ENGINEERING_TYPE'
      this.$api.projectInquiry.getTreeByTypeCode(code).then(res => {
        if (res.code == 200) {
          this.engineeringTypeList = res.data
          this.engineeringTypeList.forEach(item => {
            item.title = item.name
            if (item.children.length > 0) {
              item.children = this.getCheildItem(item.children)
            }
          })
        } else {
          this.$Message.error(res.data.msg)
        }
      })
    },
    //递归树状结构
    getCheildItem(data) {
      let item = data
      const arr = []
      item.forEach(val => {
        let obj = {}
        obj.title = val.name
        obj.code = val.code
        obj.children = []
        if (val.children.length > 0) {
          obj.children = this.getCheildItem(val)
        }
        arr.push(obj)
      })
      return arr
    },
    checkEng(data) {
      if (data[0].children.length > 0) {
        this.$Message.warning('请选择最子级节点')
      } else {
        this.list = []
        this.list1 = []
        this.wbsList = []
        this.searchParams.wbsId = ''
        let code = data[0].code
        let title = data[0].title
        this.list.push({
          code,
          title
        })
        this.searchParams.dictEngineeringType = code
        this.getWbsList(this.searchParams.dictEngineeringType)
        this.$refs.treeSelect.visible = false
      }
    },
    //获取专业类型
    getWbsList(data) {
      if (data) {
        if (this.searchParams.dictEngineeringType) {
          let res = {
            currentPage: 1,
            pageSize: 99999,
            whereMap: {
              dictEngineeringType: this.searchParams.dictEngineeringType,
              parentId: 0
            }
          }
          this.$api.projectInquiry.getWbsList(res).then(res => {
            if (res.code == 200) {
              res.data.resultObject.map(r => {
                this.$set(r, 'title', r.name)
                if (r.hasChildren) {
                  this.$set(r, 'children', [])
                  this.$set(r, 'loading', false)
                }
              })
              this.wbsList = [
                {
                  title: '标准WBS',
                  id: 0,
                  hasChildren: false,
                  loading: false,
                  expand: true,
                  children: res.data.resultObject
                }
              ]
              this.getWbsTabelList(0)
            } else {
              this.$Message.error(res.data.msg)
            }
          })
        } else {
          this.warning('请先选择工程类型')
        }
      }
    },
    loadData(item, callback) {
      let params = {
        currentPage: 1,
        pageSize: 99999,
        whereMap: {
          dictEngineeringType: this.searchParams.dictEngineeringType,
          parentId: item.id
        }
      }
      this.$api.projectInquiry.getWbsList(params).then(res => {
        if (res.code === 200) {
          callback(this.getTree(res.data.resultObject))
        } else {
          this.$Message.error(res.data.msg)
        }
      })
    },
    getTree(tree) {
      return tree.map(node => {
        node.title = node.name
        if (node.hasChildren) {
          node.loading = false
          node.children = []
        }
        return node
      })
    },
    checkWbBtn(a, b) {
      this.deleteList = [];
      this.handleNode(b);
      this.nodeItem = b;
      console.log(a, b)
      this.parentId = b.id
      this.page.current = 1
      this.page.pageSize = 10
      this.getWbsTabelList(this.parentId)
    },
    //列表
    getWbsTabelList(id) {
      let res = {
        currentPage: this.page.current,
        pageSize: this.page.pageSize,
        whereMap: {
          dictEngineeringType: this.searchParams.dictEngineeringType,
          parentId: id
        }
      }
      this.$api.projectInquiry.getWbsList(res).then(res => {
        if (res.code == 200) {
          this.dictList = res.data.resultObject
          this.page.total = res.data.totalRecord
          this.page.totalPage = res.data.totalPage
        } else {
          this.$Message.error(res.data.msg)
        }
      })
    },

    //全选
    selectRiadoAll(e) {
      this.deleteList = e
    },
    //全选取消
    selectAllCancel() {
      this.deleteList = []
    },
    //单选
    selectRiado(e) {
      this.deleteList = e
    },
    //取消某一项
    selectCancel(e) {
      this.deleteList.splice(e, 1)
    },
    pageChange(current) {
      this.page.current = current
      this.getWbsTabelList(this.parentId)
    },
    sizeChange(size) {
      this.page.current = 1
      this.page.pageSize = size
      this.getWbsTabelList(this.parentId)
    },
    //按钮显示
    buttonShow() {
      let buttonList = JSON.parse(localStorage.getItem('buttonList'))
      buttonList.map(val => {
        let key = Object.keys(val).toString()
        if (key === this.$route.name) {
          Object.values(val)[0].map(item => {
            if (item.code === 'P_0301_01') {
              this.addBtnShow = true
            } else if (item.code === 'P_0301_04') {
              this.importBtnShow = true
            } else if (item.code === 'P_0301_03') {
              this.deleteBtnShow = true
            } else {
              this.editoBtnShow = true
            }
          })
        }
      })
    }
  },
  watch: {
    $route(to, from) {
      const fromUrl = from.path
      const toUrl = to.path //标准wbs 只有一级 特殊处理
      if(fromUrl.indexOf(toUrl) > -1){
        if (fromUrl.indexOf('add') > -1 || fromUrl.indexOf('import') > -1) {
          if (localStorage.getItem('page')) {
            this.getWbsList(this.searchParams.dictEngineeringType)
            localStorage.setItem('page', '')
          }
        }
        if (fromUrl.indexOf('editor') > -1) {
          if (localStorage.getItem('page')) {
            let page = JSON.parse(localStorage.getItem('page'))
            this.page.current = page.current
            this.page.pageSize = page.pageSize
            this.getWbsTabelList(this.parentId)
            this.getWbsList(this.searchParams.dictEngineeringType);
            localStorage.setItem('page', '')
          }
        }
      }
    }
  },
  mounted() {
    this.getEngineeringType()
    this.buttonShow()
  },
  activated() {
   /* let params = {
      currentPage: 1,
      pageSize: 99999,
      whereMap: {
        dictEngineeringType: this.searchParams.dictEngineeringType,
        parentId: this.nodeItem.id
      }
    }
    this.$api.projectInquiry.getWbsList(params).then(res => {
      if (res.code === 200) {
        this.$set(this.nodeItem, 'expand', true)
        this.$set(this.nodeItem, 'children', this.getTree(res.data.resultObject))
      } else {
        this.$Message.error(res.data.msg)
      }
    })*/
  }
}
</script>

<style lang="scss" scoped>
.data-dictionary {
  height: calc(100% - 0px);
  .col-height100 {
    height: 100%;
    border-right: 1px solid #ebeef1;
    overflow: auto;

    p {
      padding: 10px;
    }
  }

  .col-main {
    padding: 10px;

    .button-s {
      margin-bottom: 15px;

      button {
        margin-right: 15px;
      }
    }
  }
}

.ul-list {
  list-style: none;
  //height: calc(100% - 10px);
  background-color: #ffffff;

  li {
    height: 45px;
    line-height: 45px;
    border-bottom: 1px solid #ebeef1;
    padding: 0 25px;
    cursor: pointer;
    font-size: 14px;
    //overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
    position: relative;

    .tooltip {
      position: absolute;
      right: 10px;
      top: 0px;
    }

    .icon {
      color: #1e88f5;
    }

    &.active {
      color: #2d8cf0;
      box-sizing: border-box;
    }
  }

  li:hover {
    color: #2d8cf0;
  }
}
</style>
